<template>
  <div class="geolocation-container">
    <h1>浏览器定位功能测试</h1>

    <div class="card">
      <h2>当前位置信息</h2>
      <div v-if="location" class="location-info">
        <p>
          <strong>纬度:</strong>
          {{ location.latitude }}
        </p>
        <p>
          <strong>经度:</strong>
          {{ location.longitude }}
        </p>
        <p>
          <strong>精度:</strong>
          {{ location.accuracy }} 米
        </p>
        <p v-if="location.altitude">
          <strong>海拔:</strong>
          {{ location.altitude }} 米
        </p>
        <p v-if="location.altitudeAccuracy">
          <strong>海拔精度:</strong>
          {{ location.altitudeAccuracy }} 米
        </p>
        <p v-if="location.heading">
          <strong>方向:</strong>
          {{ location.heading }}°
        </p>
        <p v-if="location.speed">
          <strong>速度:</strong>
          {{ location.speed }} 米/秒
        </p>
        <p>
          <strong>获取时间:</strong>
          {{ location.timestamp }}
        </p>
      </div>
      <div v-else class="no-location">
        <p>尚未获取位置信息</p>
      </div>
    </div>

    <div class="card">
      <h2>定位历史记录</h2>
      <div v-if="locationHistory.length > 0" class="history-list">
        <div v-for="(item, index) in locationHistory" :key="index" class="history-item">
          <p>
            <strong>记录 #{{ index + 1 }}</strong>
          </p>
          <p>纬度: {{ item.latitude }}, 经度: {{ item.longitude }}</p>
          <p>时间: {{ item.timestamp }}</p>
        </div>
      </div>
      <div v-else class="no-history">
        <p>暂无历史记录</p>
      </div>
    </div>

    <div class="card">
      <h2>地图显示</h2>
      <div v-if="location" class="map-container">
        <div id="map" class="map"></div>
        <p class="map-note">如果地图未显示，可能是由于网络问题或API密钥限制。 您可以将经纬度复制到其他地图服务中查看。</p>
      </div>
      <div v-else class="no-map">
        <p>获取位置后将显示地图</p>
      </div>
    </div>

    <div class="controls">
      <button @click="getCurrentLocation" :disabled="isLoading" class="btn primary">
        {{ isLoading ? '定位中...' : '获取当前位置' }}
      </button>
      <button @click="watchPosition" :disabled="isWatching" class="btn secondary">
        {{ isWatching ? '停止监听' : '开始监听位置变化' }}
      </button>
      <button @click="clearHistory" class="btn danger">清除历史记录</button>
    </div>

    <div class="card">
      <h2>定位状态</h2>
      <div class="status-info">
        <p>
          <strong>状态:</strong>
          {{ status }}
        </p>
        <p v-if="error" class="error">
          <strong>错误:</strong>
          {{ error }}
        </p>
      </div>
    </div>

    <div class="card">
      <h2>使用说明</h2>
      <div class="instructions">
        <p>1. 点击"获取当前位置"按钮获取一次位置信息</p>
        <p>2. 点击"开始监听位置变化"按钮持续监听位置变化</p>
        <p>3. 位置信息将显示在上方，并保存到历史记录</p>
        <p>4. 在移动设备上测试效果更佳</p>
        <p>5. 首次使用时浏览器会请求位置权限，请允许</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Geolocation',
  data() {
    return {
      location: null,
      locationHistory: [],
      isLoading: false,
      isWatching: false,
      status: '就绪',
      error: null,
      watchId: null
    }
  },
  mounted() {
    // 检查浏览器是否支持地理定位
    if (!navigator.geolocation) {
      this.status = '不支持'
      this.error = '您的浏览器不支持地理定位功能'
    }
  },
  methods: {
    getCurrentLocation() {
      if (!navigator.geolocation) {
        this.error = '您的浏览器不支持地理定位功能'
        return
      }

      this.isLoading = true
      this.status = '正在获取位置...'
      this.error = null

      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.handleSuccess(position)
          this.isLoading = false
        },
        (error) => {
          this.handleError(error)
          this.isLoading = false
        },
        {
          enableHighAccuracy: true, // 尝试获取最精确的位置
          timeout: 10000, // 10秒超时
          maximumAge: 60000 // 1分钟的缓存位置
        }
      )
    },

    watchPosition() {
      if (!navigator.geolocation) {
        this.error = '您的浏览器不支持地理定位功能'
        return
      }

      if (this.isWatching) {
        // 停止监听
        navigator.geolocation.clearWatch(this.watchId)
        this.isWatching = false
        this.status = '已停止监听位置变化'
      } else {
        // 开始监听
        this.status = '正在监听位置变化...'
        this.error = null

        this.watchId = navigator.geolocation.watchPosition(
          (position) => {
            this.handleSuccess(position)
          },
          (error) => {
            this.handleError(error)
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 5000 // 5秒的缓存位置
          }
        )
        this.isWatching = true
        this.status = '正在监听位置变化'
      }
    },

    handleSuccess(position) {
      const { coords, timestamp } = position
      this.location = {
        latitude: coords.latitude.toFixed(6),
        longitude: coords.longitude.toFixed(6),
        accuracy: coords.accuracy.toFixed(2),
        altitude: coords.altitude ? coords.altitude.toFixed(2) : null,
        altitudeAccuracy: coords.altitudeAccuracy ? coords.altitudeAccuracy.toFixed(2) : null,
        heading: coords.heading ? coords.heading.toFixed(2) : null,
        speed: coords.speed ? coords.speed.toFixed(2) : null,
        timestamp: new Date(timestamp).toLocaleString()
      }

      // 添加到历史记录
      this.locationHistory.unshift({ ...this.location })
      if (this.locationHistory.length > 10) {
        this.locationHistory.pop() // 只保留最近10条记录
      }

      this.status = '成功获取位置'
      this.error = null

      // 尝试加载地图
      this.$nextTick(() => {
        this.loadMap()
      })
    },

    handleError(error) {
      this.status = '获取位置失败'
      switch (error.code) {
        case error.PERMISSION_DENIED:
          this.error = '用户拒绝了位置请求'
          break
        case error.POSITION_UNAVAILABLE:
          this.error = '位置信息不可用'
          break
        case error.TIMEOUT:
          this.error = '请求位置超时'
          break
        default:
          this.error = '发生未知错误'
          break
      }
    },

    clearHistory() {
      this.locationHistory = []
    },

    loadMap() {
      // 这里可以集成第三方地图API，如百度地图、高德地图或Google Maps
      // 为了简单起见，这里只显示一个简单的静态地图链接
      const mapElement = document.getElementById('map')
      if (mapElement && this.location) {
        // 使用OpenStreetMap的静态地图（无需API密钥）
        const lat = this.location.latitude
        const lng = this.location.longitude
        const zoom = 15

        // 创建一个iframe嵌入OpenStreetMap
        mapElement.innerHTML = `
          <iframe 
            width="100%" 
            height="300" 
            frameborder="0" 
            scrolling="no" 
            marginheight="0" 
            marginwidth="0" 
            src="https://www.openstreetmap.org/export/embed.html?bbox=${lng - 0.01},${lat - 0.01},${lng + 0.01},${lat + 0.01}&layer=mapnik&marker=${lat},${lng}">
          </iframe>
        `
      }
    }
  },
  beforeUnmount() {
    // 组件销毁前清理位置监听
    if (this.watchId) {
      navigator.geolocation.clearWatch(this.watchId)
    }
  }
}
</script>

<style scoped>
.geolocation-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.card {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

h2 {
  color: #444;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.location-info p,
.status-info p {
  margin: 8px 0;
}

.history-item {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.map {
  width: 100%;
  height: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.map-note {
  font-size: 12px;
  color: #666;
  margin-top: 10px;
}

.controls {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.primary {
  background-color: #4caf50;
  color: white;
}

.primary:hover:not(:disabled) {
  background-color: #45a049;
}

.secondary {
  background-color: #2196f3;
  color: white;
}

.secondary:hover:not(:disabled) {
  background-color: #0b7dda;
}

.danger {
  background-color: #f44336;
  color: white;
}

.danger:hover {
  background-color: #d32f2f;
}

.error {
  color: #f44336;
}

.no-location,
.no-history,
.no-map {
  color: #666;
  font-style: italic;
}

.instructions {
  line-height: 1.6;
}

@media (max-width: 768px) {
  .geolocation-container {
    padding: 10px;
  }

  .controls {
    flex-direction: column;
  }

  .btn {
    width: 100%;
  }
}
</style>
